package com.wsm.kotlintest.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ProgressBar
import android.widget.TextView
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.paging.AsyncPagedListDiffer
import androidx.paging.PagedList
import androidx.paging.PagedListAdapter
import androidx.recyclerview.widget.*
import com.wsm.kotlintest.common.LOAD_MORE_STATE_ERROR
import com.wsm.kotlintest.common.LOAD_MORE_STATE_LOADING
import com.wsm.kotlintest.common.LOAD_MORE_STATE_NO_DATA
import com.wsm.kotlintest.kotlintest2.R
import com.wsm.kotlintest.model.response.redditResponseModel.Children
import com.wsm.kotlintest.viewmodel.ui.RetryCallBack

/**
 * Created by 王家宝 on 2018/7/18.
 * TEL:18241150668
 * MAIL:639586819@qq.com
 */
class HomeFragmentContentAdapter(
        var retryCallback: RetryCallBack,
        var loadMoreState: MutableLiveData<Int>,
        var lifecycleOwner: LifecycleOwner) : PagedListAdapter<Children, RecyclerView.ViewHolder>(DIFF_CONFIG) {

    private var listDiffer: AsyncPagedListDiffer<Children>
    var listUpdateCallback: AdapterListUpdateCallback = AdapterListUpdateCallback(this)

    companion object {
        private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<Children>() {
            override fun areItemsTheSame(oldItem: Children, newItem: Children): Boolean {
                return oldItem.data?.id == newItem.data?.id
            }

            override fun areContentsTheSame(oldItem: Children, newItem: Children): Boolean {
                return oldItem == newItem
            }
        }
        var DIFF_CONFIG = AsyncDifferConfig.Builder(DIFF_CALLBACK).build()

    }

    init {
        listDiffer = AsyncPagedListDiffer(object : ListUpdateCallback {
            override fun onChanged(position: Int, count: Int, payload: Any?) {
                listUpdateCallback.onChanged(position, count, payload)
            }

            override fun onMoved(fromPosition: Int, toPosition: Int) {
                listUpdateCallback.onMoved(fromPosition, toPosition)
            }

            override fun onInserted(position: Int, count: Int) {
                listUpdateCallback.onInserted(position + 1, count)
            }

            override fun onRemoved(position: Int, count: Int) {
                listUpdateCallback.onRemoved(position, count)
            }

        }, DIFF_CONFIG)

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            R.layout.item_home_fragment_content_recyclerview -> ContentViewHolder(parent)
            R.layout.network_state_item -> StateViewHolder(parent)
            else -> throw IllegalArgumentException()
        }
    }


    override fun submitList(pagedList: PagedList<Children>?) {
        listDiffer.submitList(pagedList)
    }

    override fun getItemCount(): Int {
        return listDiffer.itemCount + 1
    }

    override fun getItem(position: Int): Children? {
        return listDiffer.getItem(position)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (getItemViewType(position)) {
            R.layout.item_home_fragment_content_recyclerview -> if (getItem(position) != null) (holder as ContentViewHolder).bindTo(getItem(position), position)
            R.layout.network_state_item -> (holder as StateViewHolder)
        }
    }


    override fun getItemViewType(position: Int): Int {
        return if (position == itemCount - 1) R.layout.network_state_item else R.layout.item_home_fragment_content_recyclerview
    }

    inner class ContentViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder(
            LayoutInflater.from(parent.context).inflate(R.layout.item_home_fragment_content_recyclerview, parent, false)) {

        var name: TextView? = itemView.findViewById(R.id.tv_content)
        var testDataModel: Children? = null
        fun bindTo(testDataModel: Children?, position: Int) {
            this.testDataModel = testDataModel
            name?.text = "第${position}条  ${testDataModel?.data?.author}"
        }
    }

    inner class StateViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder(
            LayoutInflater.from(parent.context).inflate(R.layout.network_state_item, parent, false)) {

        var retryButton: Button = itemView.findViewById(R.id.retry_button)
        var progressBar: ProgressBar = itemView.findViewById(R.id.progress_bar)
        var msg: TextView = itemView.findViewById(R.id.msg)

        init {
            retryButton.setOnClickListener { retryCallback.retryOnLoadMore() }
            loadMoreState.observe(lifecycleOwner, Observer {
                retryButton.visibility =
                        if (it == LOAD_MORE_STATE_ERROR) View.VISIBLE else View.INVISIBLE
                progressBar.visibility =
                        if (it == LOAD_MORE_STATE_LOADING) View.VISIBLE else View.INVISIBLE
                msg.visibility =
                        if (it == LOAD_MORE_STATE_NO_DATA) {
                            msg.text = "没有更多数据了"
                            View.VISIBLE
                        } else View.INVISIBLE
            })
        }

    }
}